<template>
  <a-select
    :placeholder="placeholder"
    labelInValue
    show-search
    :filterOption="false"
    @focus="searchKey = ''; pageNum = 1; getLabelList()"
    @search="searchCityData"
    @popupScroll="scroll"
    :loading="searchLoading"
    v-model="cityObj"
    v-bind="options"
    @change="selectCity"
  >
    <a-select-option v-for="item in cityData" :value="item[cityKey]" :key="item[cityKey]">
      {{ item.code + '-' + item.name }}
    </a-select-option>
  </a-select>
</template>
<script>
import {tableMixins} from '@/utils/mixins'
import {getPageSimpleCityList} from '@/api/common'
import {cloneDeep, debounce} from 'lodash'

export default {
  name: 'SelectCity',
  mixins: [tableMixins],
  props: {
    placeholder: {
      type: String,
      default: '请选择城市'
    },
    value: {
      type: [String, Number],
      default: undefined
    },
    cityKey: {
      type: String,
      default: 'id'
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      cityObj: undefined,
      searchKey: '',
      searchLoading: false,
      cityData: []
    }
  },
  created() {
    this.searchCityData = debounce(this.searchCityData, 800);
  },
  methods: {
    cloneDeep,
    searchCityData(searchKey, cityObj) {
      if (cityObj) this.cityObj = cityObj
      this.searchKey = searchKey
      this.pageNum = 1
      this.getLabelList()
    },
    scroll(e) {
      const {scrollHeight, scrollTop, clientHeight} = e.target
      if (scrollHeight - scrollTop === clientHeight) {
        if (this.cityData.length === this.total) return
        this.pageNum++
        this.getLabelList()
      }
    },
    selectCity(cityObj) {
      this.$emit('change', this.cityKey === 'id' && cityObj ? cityObj.key : cityObj ? this.cityData.find(item => item.code === cityObj.key) : undefined)
    },
    getLabelList() {
      this.searchLoading = true
      getPageSimpleCityList({
        searchKey: this.searchKey.trim(),
        pageSize: this.rowsNum,
        pageNo: this.pageNum
      }).then(res => {
        this.searchLoading = false
        const {items, rowCount} = res
        this.cityData = this.pageNum === 1 ? items : this.cityData.concat(items)
        this.total = rowCount
      }).catch(() => this.searchLoading = false)
    }
  }
}
</script>
